<template>
	<view class="region-picker">
		<picker class="picker" mode="multiSelector" 
			:range="newProvinceDataList" 
			:value="multiIndex" 
			@change="pickerChange" 
			@columnchange="pickerColumnchange">
			<view class="picker-text">
				<view class="text-container">
					<text class="text-ellipsis">{{select || placeholder}}</text>
				</view>
				<text class="picker-arrow"></text>
			</view>
		</picker>
	</view>
</template>

<script>
	import { getProvinces, getCities } from '@/utils/region.js'
	
	export default {
		name: 'RegionPickerWithCheckbox',
		props: {
			modelValue: {
				type: Object,
				default: () => ({})
			},
			placeholder: {
				type: String,
				default: '工作城市'
			}
		},
		data() {
			return {
				oldProvinceDataList: [],
				newProvinceDataList: [[], []],
				multiIndex: [0, 0],
				select: '',
				provinceCode: '',
				cityCode: '',
				provinceOnly: false
			}
		},
		watch: {
			modelValue: {
				handler(newVal) {
					if (newVal && Object.keys(newVal).length > 0) {
						this.setInitialValue(newVal)
					}
				},
				immediate: true,
				deep: true
			}
		},
		created() {
			this.initData()
		},
		methods: {
			// 设置初始值
			setInitialValue(value) {
				if (!value.province) return
				
				// 查找省份索引
				const provinceIndex = this.oldProvinceDataList.findIndex(p => p.value === value.province.code)
				if (provinceIndex === -1) return
				
				// 更新省份数据
				this.multiIndex[0] = provinceIndex
				this.updatePickerData(provinceIndex)
				
				// 如果有城市信息
				if (value.city) {
					// 查找城市索引
					const cityIndex = this.oldProvinceDataList[provinceIndex].city.findIndex(c => c.value === value.city.code)
					if (cityIndex !== -1) {
						// 更新城市数据
						this.multiIndex[1] = cityIndex
						
						// 更新显示文本 - 显示城市名称
						const city = this.oldProvinceDataList[provinceIndex].city[cityIndex]
						this.select = city.name
						this.cityCode = city.value
						this.provinceOnly = false
						
						// 更新regionName字段为省份+市名称
						value.regionName = value.province.name + city.name
					}
				} else {
					// 只有省份信息，设置为只显示省份
					this.multiIndex[1] = 0
					this.select = this.oldProvinceDataList[provinceIndex].name
					this.provinceOnly = true
					
					// 更新regionName字段为省份名称
					value.regionName = value.province.name
				}
				
				// 更新省份代码
				this.provinceCode = value.province.code
			},
			
			// 更新选择器数据
			updatePickerData(provinceIndex) {
				const province = this.oldProvinceDataList[provinceIndex]
				if (!province) return
				
				// 更新省份数据
				this.newProvinceDataList[0] = this.oldProvinceDataList.map(item => item.name)
				
				// 更新城市数据
				if (province.city && province.city.length > 0) {
					this.newProvinceDataList[1] = province.city.map(item => item.name)
				} else {
					this.newProvinceDataList[1] = []
				}
			},
			
			// 初始化数据
			initData() {
				try {
					// 获取省份数据
					const provinces = getProvinces()
					if (!provinces || !provinces.length) {
						console.error('获取省份数据失败')
						return
					}
					
					// 对省份列表进行重新排序，将云南、贵州、四川、重庆和广西放在前面
					const priorityProvinces = ['云南省', '贵州省', '四川省', '重庆市', '广西壮族自治区'];
					
					// 分离出优先省份和其他省份
					const priorityList = [];
					const otherList = [];
					
					provinces.forEach(province => {
						if (priorityProvinces.includes(province.text)) {
							priorityList.push(province);
						} else {
							otherList.push(province);
						}
					});
					
					// 按照指定的顺序排序优先省份
					priorityList.sort((a, b) => {
						return priorityProvinces.indexOf(a.text) - priorityProvinces.indexOf(b.text);
					});
					
					// 合并优先省份和其他省份
					const sortedProvinces = [...priorityList, ...otherList];
					
					this.oldProvinceDataList = sortedProvinces.map(province => {
						const cities = getCities(province.value) || []
						return {
							name: province.text,
							value: province.value,
							city: cities.map(city => ({
								name: city.text,
								value: city.value
							}))
						}
					})
					
					// 初始化选择器数据
					if (this.oldProvinceDataList.length > 0) {
						this.updatePickerData(0)
						
						// 如果没有初始值，设置默认选中第一个省份
						if (!this.modelValue || Object.keys(this.modelValue).length === 0) {
							const defaultProvince = this.oldProvinceDataList[0]
							if (defaultProvince) {
								// 不设置select，保留placeholder
								// this.select = defaultProvince.name
								
								// 更新代码
								this.provinceCode = defaultProvince.value
								this.cityCode = ''
								
								// 标记只选择了省份
								this.provinceOnly = true
								
								// 构建只包含省份的简化对象
								const result = {
									province: { code: defaultProvince.value, name: defaultProvince.name },
									regionName: defaultProvince.name // 只返回省份名称
								}
								
								// 更新v-model
								this.$emit('update:modelValue', result)
							}
						}
					}
					
					// 如果有初始值，设置初始值
					if (this.modelValue && Object.keys(this.modelValue).length > 0) {
						this.setInitialValue(this.modelValue)
					}
				} catch (error) {
					console.error('初始化省市数据失败:', error)
				}
			},
			
			// 选择器确认事件
			pickerChange(e) {
				try {
					const values = e.detail.value
					if (!values || values.length !== 2) return
					
					this.multiIndex = values
					const province = this.oldProvinceDataList[values[0]]
					if (!province) return
					
					// 如果只选择了省份（provinceOnly标志被设置）
					if (this.provinceOnly) {
						// 构建只包含省份的简化对象
						const result = {
							province: { code: province.value, name: province.name },
							regionName: province.name // 只返回省份名称
						}
						
						// 触发change事件，只传递省份信息
						this.$emit('change', result)
						
						// 触发v-model更新，只传递省份信息
						this.$emit('update:modelValue', result)
						return
					}
					
					// 正常的省市选择
					const city = province.city[values[1]]
					if (!city) {
						// 如果没有选择城市，默认选择第一个城市
						if (province.city && province.city.length > 0) {
							const defaultCity = province.city[0]
							this.provinceCode = province.value
							this.cityCode = defaultCity.value
							
							// 只显示城市名称
							this.select = defaultCity.name
							
							// 选择了城市，取消省份标记
							this.provinceOnly = false
							
							// 构建包含省市的简化对象
							const result = {
								province: { code: province.value, name: province.name },
								city: { code: defaultCity.value, name: defaultCity.name },
								regionName: province.name + defaultCity.name // 返回省份+市名称
							}
							
							// 触发change事件
							this.$emit('change', result)
							
							// 触发v-model更新
							this.$emit('update:modelValue', result)
						}
						return
					}
					
					this.provinceCode = province.value
					this.cityCode = city.value
					
					// 只显示城市名称
					this.select = city.name
					
					// 选择了城市，取消省份标记
					this.provinceOnly = false
					
					// 构建包含省市的简化对象
					const result = {
						province: { code: province.value, name: province.name },
						city: { code: city.value, name: city.name },
						regionName: province.name + city.name // 返回省份+市名称
					}
					
					// 触发change事件
					this.$emit('change', result)
					
					// 触发v-model更新
					this.$emit('update:modelValue', result)
				} catch (error) {
					console.error('选择省市失败:', error)
				}
			},
			
			// 列变化事件
			pickerColumnchange(e) {
				try {
					const column = e.detail.column
					const value = e.detail.value
					
					if (column === 0) {
						// 省份改变
						this.multiIndex[0] = value
						this.multiIndex[1] = 0
						
						const province = this.oldProvinceDataList[value]
						if (!province) return
						
						// 更新省份数据
						this.newProvinceDataList[0] = this.oldProvinceDataList.map(item => item.name)
						
						// 更新城市数据
						if (province.city && province.city.length > 0) {
							this.newProvinceDataList[1] = province.city.map(item => item.name)
						} else {
							this.newProvinceDataList[1] = []
						}
						
						// 标记只选择了省份
						this.provinceOnly = true
						
						// 更新显示文本 - 显示省份名称
						this.select = province.name
						
						// 更新代码
						this.provinceCode = province.value
						this.cityCode = ''
						
						// 构建只包含省份的简化对象
						const result = {
							province: { code: province.value, name: province.name },
							regionName: province.name // 只返回省份名称
						}
						
						// 触发change事件
						this.$emit('change', result)
						
						// 更新v-model
						this.$emit('update:modelValue', result)
						
						// 强制更新视图
						this.$forceUpdate()
					} else if (column === 1) {
						// 城市变化时，取消只选择省份的标记
						this.provinceOnly = false
					}
				} catch (error) {
					console.error('省市列变化处理失败:', error)
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
.region-picker {
	.picker {
		background: #f5f7fa;
		border-radius: 8rpx;
		height: 64rpx;
		
		.picker-text {
			height: 64rpx;
			line-height: 64rpx;
			padding: 0 20rpx;
			font-size: 28rpx;
			color: #333;
			display: flex;
			align-items: center;
			justify-content: space-between;
			
			.text-container {
				flex: 1;
				min-width: 0;
				margin-right: 10rpx;
				height: 100%;
				display: flex;
				align-items: center;
				
				.text-ellipsis {
					width: 100%;
					line-height: 1;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
			}
			
			.picker-arrow {
				width: 0;
				height: 0;
				border-top: 12rpx solid #666;
				border-left: 8rpx solid transparent;
				border-right: 8rpx solid transparent;
				margin-left: 16rpx;
			}
		}
	}
}
</style> 